# get android app type
require "00_common"

INPUT_DIR   = "./android_payload/"
# OUTPUT_DIR  = "./windows_payload/"

module AndroidApps
  def self.get_all_files
  	Common.get_all_files(INPUT_DIR)
  end

  def self.get_app_name(user_agent)
    rtn = ""
    #     Mozila/_5.0_________________________________________[en]? ____________________________(......)         
    reg1 = /^([^\/[:space:]]*)(\/([^[:space:]]*))?([[:space:]]*\[[a-zA-Z][a-zA-Z]\])?[[:space:]]*\((.*)\)/

    # xxxxxxxx(xxxxxxx)
    reg2 = /^(.*)\(.*\)/

    if user_agent.match reg1
      rtn = $1 + $2
    elsif user_agent.match reg2
      rtn = $1.strip
    elsif user_agent.include? "; "
      tmp = user_agent.split("; ")
      rtn = tmp[0]
    elsif user_agent.include? ", "
      tmp = user_agent.split(", ")
      rtn = tmp[0]
    elsif user_agent.include? ", "
      tmp = user_agent.split(", ")
      rtn = tmp[0]
    elsif user_agent.include? " "
      tmp = user_agent.split(" ")
      rtn = tmp[0]
    else
      rtn = user_agent
    end

    if rtn.include? "/"
      temps = rtn.split "/"
      name = temps[0]
      version = temps[1]
      if temps.size == 2 and (version.match /[[0-9]+.]?[0-9]+/)
        rtn = name
      end
    end

    rtn
  end

  def self.handle_each_file(file_name)
    puts "now handling : " + file_name
    file = File.open INPUT_DIR + file_name, "r"

    output_mapping = Hash.new

    begin
      counter = 0
      while line = file.readline
        fields = line.split "|"
        # new_line = "#0{local_time_stamp}|#1{session_id}|#2{session_start_time}|#3{server_ip}|#4{server_port}|#5{client_ip}|#6{client_port}"
        # new_line = new_line + "|#7{referer}|#8{host}|#9{content_type}|#10{content_length}|#11{user_agent}|#{connection}|#{c_request}|#{s_response}"
        user_agent = fields[11]
        apps = get_app_name(user_agent)

        if output_mapping.has_key? apps
          output_mapping[apps] = output_mapping[apps] + 1
        else
          output_mapping[apps] = 1
        end
      end
    rescue Exception => e
      puts e.to_s
      file.close
    end

    output_mapping
  end

  def self.handle_all_files(all_files)
    mapping = Hash.new
    all_files.each do |file_name|
      output_mapping = handle_each_file(file_name)
      output_mapping.each do |key, value|
        if mapping.has_key? key
          mapping[key] = mapping[key] + value
        else
          mapping[key] = value
        end
      end
    end

    mapping
  end

  def self.output_mapping(mapping, file_name)
    output_file = File.open file_name, "w"
    mapping.each do |key, value|
      output_file.puts "#{key}|#{value}"
    end
  end
end


begin
  all_files = AndroidApps.get_all_files
  mapping =  AndroidApps.handle_all_files all_files
  AndroidApps.output_mapping mapping, "app_stat.txt"
rescue Exception => e
  puts e
end